﻿using EasyBuyShop.Utils;
using SqlSugar;

namespace EasyBuyShop.DAL
{
    public class BaseDal
    {

        public static string ConnStr = string.Empty;
        /// <summary>
        /// 获取程序数据库操作对象
        /// </summary>
        /// <param name="strConn">数据库连接字符串</param>
        /// <returns></returns>
        public SqlSugarClient GetDb(string strConn)
        {
            var db = new SqlSugarClient(
                new ConnectionConfig()
                {
                    ConnectionString = strConn,
                    DbType = DbType.SqlServer,
                    IsAutoCloseConnection = true,
                    InitKeyType = InitKeyType.Attribute,
                    AopEvents = new AopEvents
                    {
                        OnLogExecuting = (sql, p) =>
                        {
                            LogHelper.Info(sql);
                            LogHelper.Info(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
                        }
                    }
                });
            return db;
        }



        /// <summary>
        /// 查询所有的用户记录
        /// </summary>
        /// <returns></returns>
        public List<T> getTList<T>()
        {
            try
            {
                return this.GetDb(ConnStr).Queryable<T>().ToList();
            }
            catch (Exception ex)
            {
                LogHelper.Fatal(ex.Message);
                return null;
            }
        }


        /// <summary>
        /// 插入一条记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public int InsertT<T>(T model) where T : class, new()
        {
            try
            {
                return this.GetDb(ConnStr).Insertable<T>(model).ExecuteCommand();
            }
            catch (Exception ex)
            {
                LogHelper.Fatal(ex.Message);
                return -1;
            }
        }

    }
}
